﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;

namespace SPBusiness
{
    public delegate void CodeToRun();

    public sealed class ManagedRun
    {
       /// <summary>
       /// ManagedRun class has only Static Methods, no constructor needed.
       /// </summary>
       private ManagedRun() { }

        public static void RunWithRetries(CodeToRun pCodeToRun, int pMaxExecutions, int pDelayBetweenExecutions, string pNameSpace, string pClass, string pMethod)
        {
            bool vExecuted = false;
            Int32 vExecutions = 0;

            while (!vExecuted && vExecutions < 5)
            {
                try
                {
                    Run(new WaitCallback(CodeToRunWrapper), pCodeToRun);
                    vExecuted = true;
                    if (vExecutions > 0)
                    {
                        Logging.LogMessase(pNameSpace, pClass, pMethod, new Exception("Operation successfully after " + (vExecutions + 1).ToString() + " retries."));
                    }
                }
                catch (Exception ex)
                {
                    vExecutions += 1;
                    Logging.LogMessase(pNameSpace, pClass, pMethod, ex);

                    if (vExecutions == pMaxExecutions)
                    {
                        throw new Exception("Maximum retries quantity reached.", ex);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(pDelayBetweenExecutions);
                    }
                }
            }


        }

        private static void CodeToRunWrapper(object state)
        {
            ((CodeToRun)state)();
        }

        internal static void Run(WaitCallback pWaitCallback, object param)
        {
            pWaitCallback(param);
        }

    }
}
